package com.xh.common.thread.ext.executor;

public class Command implements ThreadPolicy, Runnable, Comparable<Command> {

    private int mLevel;
    private int mPriority;
    private int mThreadPriority;
    private long mSequence;

    private Runnable mRunnable;

    public Command(Runnable runnable) {
        this(runnable, null);
    }

    public Command(Runnable runnable, ThreadPolicy policy) {
        mRunnable = runnable;

        if (policy != null) {
            mLevel = policy.getLevel();
            mPriority = policy.getPriority();
            mThreadPriority = policy.getThreadPriority();
        }
    }

    public Runnable getRunnable() {
        return mRunnable;
    }

    @Override
    public int getThreadPriority() {
        return mThreadPriority;
    }

    public void setSequence(long sequence) {
        mSequence = sequence;
    }

    public long getSequence() {
        return mSequence;
    }

    @Override
    public int getPriority() {
        return mPriority;
    }

    @Override
    public int getLevel() {
        return mLevel;
    }

    @Override
    public void run() {
        mRunnable.run();
    }

    @Override
    public int compareTo(Command o) {
        // level高的在前面
        if (mLevel != o.getLevel()) {
            return - (mLevel - o.getLevel());
        }

        // 优先级高的在前面
        if (mPriority != o.getPriority()) {
            return - (mPriority - o.getPriority());
        }

        return (int) (mSequence - o.getSequence());
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Runnable = ").append(mRunnable).append(", ");
        builder.append("Level = ").append(mLevel).append(", ");
        builder.append("Priority = ").append(mPriority).append(", ");
        builder.append("ThreadPriority = ").append(mThreadPriority).append(", ");
        builder.append("Sequence = ").append(mSequence);

        return builder.toString();
    }
}
